local skynet = require "skynet"
local cjson = require "cjson"
local datacenter = require "skynet.datacenter"
require "skynet.manager"
local send_request

local CMD   = {}
local ROOMS = {}
local count = 0

local function dispatch_package(a,pack)
    local ok = pcall(skynet.send, a,"lua","native_dispatch",pack)
end


function CMD.dismiss(roomid)
    skynet.error("解散房间",roomid,type(roomid))

    for k,v in pairs(ROOMS) do
        skynet.error("k=",type(k),k)
    end

    ROOMS[roomid] = nil

    for k,v in pairs(ROOMS) do
        skynet.error("k=",type(k),k)
    end

    return "ok"
end

function CMD.join(agent, roomid, uid)
    skynet.error(string.format(" user %s join room %s u type %s ",tostring(uid),tostring(roomid), type(uid)))
    if not ROOMS[roomid] then
        local room    = skynet.newservice("room", roomid)
        ROOMS[roomid] = room
        skynet.call(room,"lua","start",{}, skynet.self())
    end
    local room = ROOMS[roomid]
    local ok   = pcall(skynet.call, room,"lua", "join", agent, uid)
    if not ok then
        dispatch_package(agent, {c="game", m="login",data={errcode=10001, errmsg="系统繁忙, 请稍等后再试"}})
        return "ng"
    end
    return "ok"
end


function CMD.sendmsg(roomid, msg_type, msg)
    local room = ROOMS[roomid]
    if not room then
        return "ng"
    end
    local ok = skynet.call(room, "lua", "sendmsg", msg_type, msg)
    skynet.error("sendmsg ok = ", ok)
    return "ok"
end

skynet.start(function()
    skynet.dispatch("lua", function(_,_, command, ...)
        -- skynet.trace()
        local f = CMD[command]
        skynet.ret(skynet.pack(f(...)))
    end)

    skynet.register "roommgr"
end)
